<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/16 10:20
 */

namespace App\Project\Filters;

class ComplaintFilter extends FilterAbstract
{
    //  症状组数据处理，当一组症状内的字段全部为空时，去掉该组
    protected function forExtend()
    {
        $map      = [];
        $symptoms = collect($this->request->input('symptoms'));

        if ($symptoms->count()) {
            $symptoms->map(function ($symptom, $key) use (&$map) {

                $map['symptoms'][$key] = array_flip(['name', 'started_at', 'exacerbated_at']);

                if (isset($symptom['name']) && count($symptom['name']) > 0) {
                    $count                         = count($symptom['name']);
                    $map['symptoms'][$key]['name'] = array_pad((array)$map['symptoms'][$key]['name'], $count, 0);
                }
            });
        }

        $map['medication']    = $this->medication($this->request->input('medication'));
        $map['cn_medication'] = $this->cnMedication();

        return $map;
    }

    protected function medication($medication)
    {
        if (empty($medication)) {
            return 1;
        }
        $map = [];

        if (is_array($medication)) {
            foreach ($medication as $key => $item) {
                $map[$key] = array_flip([
                    'name', 'dosage.type', 'dosage.value', 'dosage.values.morning',
                    'dosage.unit', 'start_time', 'end_time', 'usage',
                    'frequency', 'remark', 'dosage.values.atnoon', 'dosage.values.evening',
                    'dosage.values.before_sleep'
                ]);
            }
        }

        return $map;
    }

    protected function cnMedication()
    {
        $map = [];

        $medication = $this->request->input('cn_medication');

        if (is_array($medication) && ($count = count($medication)) > 0) {

            $keys = [];

            for ($i = 0; $i < $count; $i++) {

                $drugs = count($medication[$i]['drugs']);

                for ($j = 0; $j < $drugs; $j++) {
                    $keys[$j] = array_flip(['name', 'weight']);
                }

                $map[$i] = array_merge(array_flip(['usage', 'dosage', 'frequency', 'dose']), ['drugs' => $keys]);
            }
        }

        return $map;
    }

    protected function getRootFieldsHasNoSon()
    {
        return [
            'id',
            'record_id',
            'blood_glucose',
            'weightchange',
            'weightchangestatus',
            'weightchangekg',
            'remark',
        ];
    }

    protected function getRootFieldsHasSon()
    {
        return ['blood_glucose'];
    }

    protected function getSonFieldsForEachRoot()
    {
        return ['limosis.low', 'limosis.high', 'postprandial.low', 'postprandial.high',];
    }
}